package com.wn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wn.bean.*;
import com.wn.service.IRoleService;
import com.wn.service.IUserRoleService;
import com.wn.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-16
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @GetMapping
    public R queryAll(){

        log.info("queryAll");

        List<User> list = userService.list();

        R r = new R();

        if (!CollectionUtils.isEmpty(list)){
            r.setData(list);
            r.setMsg("操作成功");
            r.setCode(Constants.SUCCESS_CODE);
            return r;
        }

        return R.ERROR("没有数据");

    }

    @PostMapping
    public R addUser(@RequestBody User user){

        /**
         *
         * 添加用户
         * 01  用户加密
         *
         * 02  用户中有rid
         *       rid存储在
         */
        return  userService.saveUser(user);
    }

    @DeleteMapping("/{uid}")
    public R deleteUserById(@PathVariable Integer uid){
        return userService.deleteUserById(uid);
    }

    /**
     *
     * 这个注解添加授权操作
     * RequiresPermissions("user:delete")  权限
     * 01 shiroConfig  中配置
     *
     *   DefaultAdvisorAutoProxyCreator         配置 aop的操作
     *
     *    AuthorizationAttributeSourceAdvisor   匹配所有加了权限注解的方法，让权限校验注解生效。注入SecurityManager
     *
     * @return
     */
    @RequiresPermissions({"user:delete"})
    @DeleteMapping
    public R delete(){
        return R.OK("删除成功");
    }

    @RequiresPermissions("user:list")
    @GetMapping("/{uid}")
    public R findUserById(@PathVariable Integer uid){

        /**
         *  查询 user
         *  查询 userRole
         *
         *  {
         *      username:zhang,
         *      password:123,
         *      rid:1
         *  }
         */
        User user = userService.getById(uid);

        QueryWrapper<UserRole> qr = new QueryWrapper<>();
        qr.eq("uid",user.getUid());
        UserRole userRole = userRoleService.getOne(qr);
        Integer rid = userRole.getRid();
        user.setRid(rid);

        R r = new R();
        r.setCode(Constants.SUCCESS_CODE);
        r.setMsg("成功");
        r.setData(user);
        return r;

    }
}

